package com.doudou.mybatis.mate.core.dialect.support;

import com.doudou.mybatis.mate.core.dialect.IDialectHandler;
import com.doudou.mybatis.mate.core.entity.Page;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.session.RowBounds;

import java.util.Map;
import java.util.Set;

/**
 * MySqlDialectHandler
 *
 * @author jiangcs
 * @since 2022/4/2
 */
public class MySqlDialectHandler implements IDialectHandler {
    @Override
    public BoundSql getCountSql(MappedStatement mappedStatement, Object parameterObject, BoundSql boundSql, Map<String, Object> additionalParameterMap) {
        String countSql = "select count(*) as count from (" + boundSql.getSql() + ") tmp";
        // todo 去掉 order by
        // todo 优化 left join
        BoundSql countBoundSql = new BoundSql(mappedStatement.getConfiguration(), countSql, boundSql.getParameterMappings(), parameterObject);

        // 参数
        Set<String> keySet = additionalParameterMap.keySet();
        for (String key : keySet) {
            countBoundSql.setAdditionalParameter(key, additionalParameterMap.get(key));
        }

        System.out.println("countSql:" + countSql);
        return countBoundSql;
    }

    @Override
    public BoundSql getPageSql(MappedStatement mappedStatement, Object parameterObject, BoundSql boundSql, Map<String, Object> additionalParameterMap, Page page) {
        // offset，count
        int offset, count;
        RowBounds rowBounds = page.getRowBounds();
        if (rowBounds != null) {
            offset = rowBounds.getOffset();
            count = rowBounds.getLimit();
        } else {
            offset = (page.getPageNum() - 1) * page.getPageSize();
            count = page.getPageSize();
        }

        String pageSql = boundSql.getSql() + " limit " + offset + "," + count;
        BoundSql pageBoundSql = new BoundSql(mappedStatement.getConfiguration(), pageSql, boundSql.getParameterMappings(), parameterObject);

        // 参数
        Set<String> keySet = additionalParameterMap.keySet();
        for (String key : keySet) {
            pageBoundSql.setAdditionalParameter(key, additionalParameterMap.get(key));
        }
        System.out.println("pageSql:" + pageSql);
        return pageBoundSql;
    }
}
